package com.qd.panda.service.card.third.sync;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.card.third.sync.ThirdPartyListDTO;
import com.qd.panda.mapper.card.ThirdPartyListMapper;
import com.qd.panda.model.ThirdPartyList;
import com.qd.panda.service.card.third.ThirdPartyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 劵列表
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ThirdPartyListService extends BaseService<ThirdPartyListMapper, ThirdPartyList> {

    private static final String PREFIX_ID = "panda_third_party_list_thirdCouponCode_{0}";

    private final RedisTemplateUtil<ThirdPartyList> redisTemplateUtil;
    private final ThirdPartyService thirdPartyService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ThirdPartyListDTO save(ThirdPartyListDTO dto) {
        final ThirdPartyList model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ThirdPartyListDTO update(ThirdPartyListDTO dto) {
        final ThirdPartyList historyModel = Optional.ofNullable(getById(dto.getThirdCouponCode())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final ThirdPartyList model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ThirdPartyList> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    public void updateBatchIds(List<ThirdPartyList> mList) {
        final List<String> ids = mList.stream().map(ThirdPartyList::getThirdCouponCode).collect(toList());
        final List<ThirdPartyList> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param thirdCouponCode 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String thirdCouponCode) {
        final ThirdPartyList historyModel = Optional.ofNullable(getById(thirdCouponCode)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(thirdCouponCode)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<ThirdPartyList> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(ThirdPartyListDTO dto) {
        final QueryWrapper<ThirdPartyList> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param thirdCouponCode 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String thirdCouponCode) {
        boolean exists = false;
        if (StringUtils.hasLength(thirdCouponCode)) {
            final ThirdPartyList model = getById(thirdCouponCode);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param thirdCouponCode 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public ThirdPartyList getById(String thirdCouponCode) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, thirdCouponCode);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(thirdCouponCode), ThirdPartyList.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param thirdCouponCode 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ThirdPartyListDTO getByIdDto(String thirdCouponCode) {
        return Optional.ofNullable(getById(thirdCouponCode)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public ThirdPartyList getOne(ThirdPartyListDTO dto) {
        final QueryWrapper<ThirdPartyList> queryWrapper = createQueryWrapper(dto);
        ThirdPartyList model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ThirdPartyListDTO getOneDto(ThirdPartyListDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<ThirdPartyList> getList(ThirdPartyListDTO dto) {
        final QueryWrapper<ThirdPartyList> queryWrapper = createQueryWrapper(dto);
        final List<ThirdPartyList> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<ThirdPartyListDTO> getListDto(ThirdPartyListDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<ThirdPartyListDTO> page(Page<ThirdPartyList> page, ThirdPartyListDTO dto) {
        final QueryWrapper<ThirdPartyList> queryWrapper = createQueryWrapper(dto);
        Page<ThirdPartyList> iPage = baseMapper.selectPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(this::modelToDtoList);
        queryWrapper.clear();
        return iPage.convert(this::modelToDto);
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(ThirdPartyList model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getThirdCouponCode()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<ThirdPartyList> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getThirdCouponCode())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public ThirdPartyListDTO modelToDto(ThirdPartyList model) {
        if (null == model) {
            return null;
        }
        final ThirdPartyListDTO dto = new ThirdPartyListDTO();
        dto.setThirdCouponCode(model.getThirdCouponCode());
        dto.setRedemptionTime(model.getRedemptionTime());
        dto.setUseTime(model.getUseTime());
        dto.setState(model.getState());
        dto.setEvent(model.getEvent());
        dto.setCardId(model.getCardId());
        dto.setThirdParty(model.getThirdParty());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public ThirdPartyList dtoToModel(ThirdPartyListDTO dto) {
        if (null == dto) {
            return null;
        }
        final ThirdPartyList model = new ThirdPartyList();
        model.setThirdCouponCode(dto.getThirdCouponCode());
        model.setRedemptionTime(dto.getRedemptionTime());
        model.setUseTime(dto.getUseTime());
        model.setState(dto.getState());
        model.setEvent(dto.getEvent());
        model.setCardId(dto.getCardId());
        model.setThirdParty(dto.getThirdParty());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ThirdPartyListDTO dto) {
        String stateDisplay = "";
        switch (dto.getState()) {
            case PandaConstant.USE_STATE_NEG_1:
                stateDisplay = "未分配";
                break;
            case PandaConstant.USE_STATE_0:
                stateDisplay = "未兑换";
                break;
            case PandaConstant.USE_STATE_1:
                stateDisplay = "已兑换";
                break;
            case PandaConstant.USE_STATE_2:
                stateDisplay = "已使用";
                break;
            case PandaConstant.USE_STATE_3:
                stateDisplay = "已过期";
                break;
            default:
                break;
        }
        dto.setStateDisplay(stateDisplay);
        dto.setThirdPartyDisplay(thirdPartyService.idToDisplay(dto.getThirdParty()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<ThirdPartyListDTO> modelToDtoList(List<ThirdPartyList> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<ThirdPartyList> dtoToModelList(List<ThirdPartyListDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<ThirdPartyList> createQueryWrapper(ThirdPartyListDTO dto) {
        final QueryWrapper<ThirdPartyList> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(dto.getEvent())) {
                queryWrapper.eq("event", dto.getEvent());
            }
            if (null != dto.getState()) {
                queryWrapper.eq("state", dto.getState());
            }
            if (StringUtils.hasLength(dto.getCardId())) {
                queryWrapper.eq("card_id", dto.getCardId());
            }
            if (StringUtils.hasLength(dto.getThirdCouponCode())) {
                queryWrapper.eq("third_coupon_code", dto.getThirdCouponCode());
            }
            if (StringUtils.hasLength(dto.getThirdParty())) {
                queryWrapper.eq("third_party", dto.getThirdParty());
            }
        }
        queryWrapper.orderByAsc("event");
        queryWrapper.orderByDesc("state");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<ThirdPartyList> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<ThirdPartyList> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(ThirdPartyList::getThirdCouponCode).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public List<ThirdPartyList> getListByEvent(String event) {
        QueryWrapper<ThirdPartyList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("event", event);
        List<ThirdPartyList> thirdPartyLists = baseMapper.selectList(queryWrapper);
        queryWrapper.clear();
        return thirdPartyLists;
    }

    public List<ThirdPartyList> getListByCardIds(List<String> cardIds) {
        QueryWrapper<ThirdPartyList> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("card_id", cardIds);
        queryWrapper.eq("state", PandaConstant.USE_STATE_0);
        List<ThirdPartyList> thirdPartyLists = getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        return thirdPartyLists;
    }

    @Transactional(readOnly = true)
    public ThirdPartyListDTO getListByCardIdDto(String cardId) {
        QueryWrapper<ThirdPartyList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", cardId);
        ThirdPartyList one = getOne(queryWrapper, false);
        queryWrapper.clear();
        return modelToDto(one);
    }

    /**
     * 清理过期的优惠券
     *
     * @param cardIds 券集合
     */
    public void clearUp(List<String> cardIds) {
        List<ThirdPartyList> list = getListByCardIds(cardIds);
        if (!list.isEmpty()) {
            list.forEach(thirdPartyList -> thirdPartyList.setState(PandaConstant.USE_STATE_3));
            updateBatchIds(list);
            list.clear();
        }
    }
}